﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class TestAudioPlay : MonoBehaviour
{
    public string url;
    public int channels = 2;
    public int channelLayout = 3;
    public int sampleRate = 44100;
    public int sampleFormat = 8;
    private SCAudioPlay audioPlay;
    private FileStream fs;
    private bool isPause = false;
    private byte[] buffer;
    public Button openBtn, pauseBtn, closeBtn;
    // Use this for initialization
    void Start()
    {
        audioPlay = new SCAudioPlay();
        try
        {
            fs = new FileStream(url, FileMode.Open);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.ToString());
        }

        openBtn.onClick.AddListener(Open);
        pauseBtn.onClick.AddListener(Pause);
        closeBtn.onClick.AddListener(Close);
    }

    private void Open()
    {
        isPause = false;
        pauseBtn.GetComponentInChildren<Text>().text = isPause ? "Play" : "Pause";

        AudioStream stream = new AudioStream();
        stream.streamCount = 1;
        stream.channels = channels;
        stream.channel_layout = channelLayout;
        stream.samplerate = sampleRate;
        stream.samplefmt = sampleFormat;
        audioPlay.OpenAsync(stream, OpenCb, PlayCb);
    }

    private void OpenCb(AudioPlayParams app)
    {
        buffer = new byte[app.hwSize];
        audioPlay.Start();
    }

    private void Pause()
    {
        isPause = !isPause;
        pauseBtn.GetComponentInChildren<Text>().text = isPause ? "Play" : "Pause";
    }

    private void Close()
    {
        audioPlay.Close();
    }
    private void PlayCb(IntPtr stream, int len)
    {
        if (SCInstance.isPaused)
        {
            audioPlay.Memset(stream, 0, len);
            return;
        }

        if (fs.Read(buffer, 0, len) != len)
        {
            fs.Seek(0, SeekOrigin.Begin);
            fs.Read(buffer, 0, len);
        }
        if (isPause)
        {
            audioPlay.Memset(stream, 0, len);
            return;
        }
        audioPlay.MixAudioFormat(stream, buffer, len, 1.0f);
    }

    private void OnDestroy()
    {
        audioPlay.Release();
        audioPlay = null;
        fs.Close();
    }
}
